/**
 * UniApp API Promise 封装
 * @module Async
 * @example
 * import uniAsync from '@/common/sju.async.js'
 * 
 * // 方式1: Promise调用
 * uniAsync.request({url: 'api/example', data: {}})
 *   .then(res => console.log(res))
 *   .catch(err => console.error(err))
 * 
 * // 方式2: async/await调用
 * async function fetchData() {
 *   try {
 *     const res = await uniAsync.request({url: 'api/example'})
 *   } catch(err) {
 *     console.error(err)
 *   }
 * }
 */

const uniAsync = new Proxy({}, {
  get(target, name) {
    if (!uni[name] || typeof uni[name] !== 'function') {
      return () => Promise.reject(new Error(`UniApp API ${String(name)} 不存在`))
    }

    return (params = {}) => new Promise((resolve, reject) => {
      const startTime = Date.now()
      
      uni[name]({
        ...params,
        success: (res) => {
          console.debug(`[API Success] ${name}`, {
            params,
            response: res,
            duration: `${Date.now() - startTime}ms`
          })
          resolve(res)
        },
        fail: (err) => {
          console.error(`[API Failed] ${name}`, {
            params,
            error: err,
            duration: `${Date.now() - startTime}ms`
          })
          reject(err)
        },
        complete: () => {
          console.log(`[API Completed] ${name} in ${Date.now() - startTime}ms`)
        }
      })
    })
  }
})

export default uniAsync
